package com.ai.analysis;

import com.ai.tool.CacheConst;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.SnThread;

/**
 * @Description 负责记录语音翻译
 * @ClassName Noter
 * @Date 2017年1月22日 下午2:44:54
 * @Author yanghao Copyright (c) All Rights Reserved, 2017.
 */
public class Noter extends SnThread {

	private boolean goon = false;

	public Noter() {
		goon = true;
		this.start();
	}

	public void run() {
		while (goon) {
			sleep(5);
			readResult();
//			String msg = readResult();
//			if (msg != null && !"".equals(msg)) {
//				System.out.println("语音输入：" + msg);
//				// StoreHouse.addUse(msg);
//				// Calculator.addNumber(msg);
//				keyCheck(msg);
//			}
		}
	}

	/**
	 * @Description 关键字检查
	 * @param 参数
	 * @return void 返回类型
	 * @throws
	 */
	public void keyCheck(String bag) {
		CacheConst.kls.distTask(bag);
	}

	private void readResult() {
		String text = StoreHouse.getRaw();
		if (text != null) {
			JSONObject json = JSON.parseObject(text);
			if (json.getString("operation").equals("QUERY")) {
				readQuery(json);
			}if (json.getString("operation").equals("ANSWER")) {
				readAnswer(json);
			}else{
				readVoice(json);
			}
		} 
	}

	/**
	 * @Description TODO
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	private String readVoice(JSONObject json) {
		String msg = null;
		try {
			StringBuffer bf = new StringBuffer();
			JSONArray arr1 = json.getJSONArray("ws");
			for (int i = 0; i < arr1.size(); i++) {
				JSONObject json2 = arr1.getJSONObject(i);
				JSONArray arr2 = json2.getJSONArray("cw");
				for (int j = 0; j < arr2.size(); j++) {
					JSONObject json3 = arr2.getJSONObject(j);
					String v = json3.getString("w");
					bf.append(v);
				}
			}
			msg = bf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}

	private String readQuery(JSONObject json) {
		JsonReader jsonReader = new JsonReader();
		String msg = null;
		try {
			msg = jsonReader.readQuery(json);
			CacheConst.getSpeeker().say(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}
	
	private String readAnswer(JSONObject json) {
		JsonReader jsonReader = new JsonReader();
		String msg = null;
		try {
			msg = jsonReader.readAnswer(json);
			CacheConst.getSpeeker().say(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}

}
